/*!
    \file    gd32f4xx_it.c
    \brief   interrupt service routines

    \version 2024-12-20, V3.3.1, firmware for GD32F4xx
*/

/*
    Copyright (c) 2024, GigaDevice Semiconductor Inc.

    Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

    1. Redistributions of source code must retain the above copyright notice, this
       list of conditions and the following disclaimer.
    2. Redistributions in binary form must reproduce the above copyright notice,
       this list of conditions and the following disclaimer in the documentation
       and/or other materials provided with the distribution.
    3. Neither the name of the copyright holder nor the names of its contributors
       may be used to endorse or promote products derived from this software without
       specific prior written permission.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
OF SUCH DAMAGE.
*/

#include "gd32f4xx_it.h"
#include "main.h"
#include "systick.h"

/*!
    \brief      this function handles NMI exception
    \param[in]  none
    \param[out] none
    \retval     none
*/
void NMI_Handler(void)
{
    /* if NMI exception occurs, go to infinite loop */
    while(1) {
    }
}

// 定义用于存储 HardFault 寄存器信息的结构体
struct
{
    volatile uint32_t r0;
    volatile uint32_t r1;
    volatile uint32_t r2;
    volatile uint32_t r3;
    volatile uint32_t r12;
    volatile uint32_t lr;
    volatile uint32_t pc;
    volatile uint32_t psr;
    volatile uint32_t exc_return;
} volatile hardfault_info = { 0 };


void PrintRegisterDump(void)
{
    int printf(const char *format, ...);

    printf("hard fault before register dump:\n");
    printf("r0: %08x,\nr1: %08x,\nr2: %08x,\nr3: %08x,\n"
           "r12: % 08x,\nlr: % 08x,\npc: % 08x,\npsr: % 08x,\n"
           "exc_return: % 08x\n",
        hardfault_info.r0, hardfault_info.r1,
        hardfault_info.r2, hardfault_info.r3,
        hardfault_info.r12, hardfault_info.lr,
        hardfault_info.pc, hardfault_info.psr,
        hardfault_info.exc_return);
}

void FaultRepo(void)
{
    int printf(const char *format, ...);

    printf("fault repo:\n");
    /* 由存储管理错误触发的hardfault */
    printf("    MemManage Fault:\n");
    if(SCB->CFSR & (0x1 << 0U)) // 指令访问冲突
        printf("        IACCVIOL:1\n");
    else
        printf("        IACCVIOL:0\n");
    if(SCB->CFSR & (0x1 << 1U)) // 数据访问冲突
        printf("        DACCVIOL:1\n");
    else
        printf("        DACCVIOL:0\n");
    if(SCB->CFSR & (0x1 << 3U)) // 出栈错误
        printf("        MUNSTKERR:1\n");
    else
        printf("        MUNSTKERR:0\n");
    if(SCB->CFSR & (0x1 << 4U)) // 压栈错误
        printf("        MSTKERR:1\n");
    else
        printf("        MSTKERR:0\n");
    if(SCB->CFSR & (0x1 << 5U)) // 浮点惰性压栈错误
        printf("        MLSPERR:1\n");
    else
        printf("        MLSPERR:0\n");
    if(SCB->CFSR & (0x1 << 7U)) // MemManage错误地址
    {
        printf("        MMFAR:%08x\n", SCB->MMFAR);
    }

    /* 由总线错误的hardfault */
    printf("    Bus Fault:\n");
    if(SCB->CFSR & (0x1 << 8U)) // 指令访问冲突
        printf("        IBUSERR:1\n");
    else
        printf("        IBUSERR:0\n");
    if(SCB->CFSR & (0x1 << 9U)) // 精确的数据访问冲突
        printf("        PRECISERR:1\n");
    else
        printf("        PRECISERR:0\n");
    if(SCB->CFSR & (0x1 << 10U)) // 不精确的数据访问冲突
        printf("        IMPRECISERR:1\n");
    else
        printf("        IMPRECISERR:0\n");
    if(SCB->CFSR & (0x1 << 11U)) // 出栈错误
        printf("        UNSTKERR:1\n");
    else
        printf("        UNSTKERR:0\n");
    if(SCB->CFSR & (0x1 << 12U)) // 压栈错误
        printf("        STKERR:1\n");
    else
        printf("        STKERR:0\n");
    if(SCB->CFSR & (0x1 << 13U)) // 浮点惰性压栈错误
        printf("        LSPERR:1\n");
    else
        printf("        LSPERR:0\n");
    if(SCB->CFSR & (0x1 << 15U)) // 总线错误地址
        printf("        BFAR:%08x\n", SCB->BFAR);

    /* 由使用错误触发的hardfault */
    printf("    Usage Fault:\n");
    if(SCB->CFSR & (0x1 << 16U)) // 试图执行未定义指令
        printf("        UNDEFINSTR:1\n");
    else
        printf("        UNDEFINSTR:0\n");
    if(SCB->CFSR & (0x1 << 17U)) // 试图切换到错误状态
        printf("        INVSTATE:1\n");
    else
        printf("        INVSTATE:0\n");
    if(SCB->CFSR & (0x1 << 18U)) // 试图执行EXC_RETURN错误的异常
        printf("        INVPC:1\n");
    else
        printf("        INVPC:0\n");
    if(SCB->CFSR & (0x1 << 19U)) // 试图执行协处理器指令
        printf("        NOCP:1\n");
    else
        printf("        NOCP:0\n");
    if(SCB->CFSR & (0x1 << 24U)) // 非对齐访问错误
        printf("        UNALIGNED:1\n");
    else
        printf("        UNALIGNED:0\n");
    if(SCB->CFSR & (0x1 << 25U)) // 除零错误
        printf("        DIVBYZERO:1\n");
    else
        printf("        DIVBYZERO:0\n");

    /* 由取向量失败触发的hardfault */
    if(SCB->HFSR & (0x1 << 1U))
    {
        printf("    VECTBL:1\n");
    }
    else
    {
        printf("    VECTBL:0\n");
    }
}

/*!
    \brief    this function handles HardFault exception
    \param[in]  none
    \param[out] none
    \retval     none
*/
__asm void HardFault_Handler(void)
{
    PRESERVE8

    TST LR, #4          // 检查EXC_RETURN[2]确定堆栈指针
    ITE EQ
    MRSEQ R0, MSP       // 主堆栈指针
    MRSNE R0, PSP       // 进程堆栈指针

    IMPORT hardfault_info
    LDR R2, =hardfault_info

    // 批量加载寄存器值
    LDMIA R0!, { R3, R12 }   // 加载R0-R1到临时寄存器
    STMIA R2!, { R3, R12 }   // 存储R0-R1
    LDMIA R0!, { R3, R12 }   // 加载R2-R3
    STMIA R2!, { R3, R12 }   // 存储R2-R3
    LDMIA R0!, { R3, R12 }   // 加载R12-LR
    STMIA R2!, { R3, R12 }   // 存储R12-LR

    // 单独处理最后3个寄存器
    LDMIA R0!, { R3, R12 }   // 加载PC-PSR
    STR R3, [R2], #4       // 存储PC
    STR R12, [R2], #4      // 存储PSR
    STR LR, [R2]           // 存储EXC_RETURN


    /* 打印转储信息 */
    IMPORT PrintRegisterDump
    PUSH { R0 - R3, LR }       // 统一保存工作寄存器
    BL PrintRegisterDump
    POP { R0 - R3, LR }

    /* 打印fault报告 */
    IMPORT FaultRepo
    PUSH { R0 - R3, LR }       // 统一保存工作寄存器
    BL FaultRepo
    POP { R0 - R3, LR }

    B .
}

/*!
    \brief      this function handles MemManage exception
    \param[in]  none
    \param[out] none
    \retval     none
*/
void MemManage_Handler(void)
{
    /* if Memory Manage exception occurs, go to infinite loop */
    while(1) {
    }
}

/*!
    \brief      this function handles BusFault exception
    \param[in]  none
    \param[out] none
    \retval     none
*/
void BusFault_Handler(void)
{
    /* if Bus Fault exception occurs, go to infinite loop */
    while(1) {
    }
}

/*!
    \brief      this function handles UsageFault exception
    \param[in]  none
    \param[out] none
    \retval     none
*/
void UsageFault_Handler(void)
{
    /* if Usage Fault exception occurs, go to infinite loop */
    while(1) {
    }
}

/*!
    \brief      this function handles SVC exception
    \param[in]  none
    \param[out] none
    \retval     none
*/
void SVC_Handler(void)
{
    /* if SVC exception occurs, go to infinite loop */
    while(1) {
    }
}

/*!
    \brief      this function handles DebugMon exception
    \param[in]  none
    \param[out] none
    \retval     none
*/
void DebugMon_Handler(void)
{
    /* if DebugMon exception occurs, go to infinite loop */
    while(1) {
    }
}

/*!
    \brief      this function handles PendSV exception
    \param[in]  none
    \param[out] none
    \retval     none
*/
void PendSV_Handler(void)
{
    /* if PendSV exception occurs, go to infinite loop */
    while(1) {
    }
}

/*!
    \brief    this function handles SysTick exception
    \param[in]  none
    \param[out] none
    \retval     none
*/
void SysTick_Handler(void)
{
    extern volatile uint32_t tick;
    tick++;
    delay_decrement();
}
